<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script>
        // 获取分页数据
        $(function () { // DOM 加载完毕默认要执行的函数
            $.ajax({
                url:"user/users",
                data:"pn=1",
                type:"get",
                success:function (result) {
                    $("#currentPage").text(result.pageNum);
                    $("#pages").text(result.pages);
                    $("#total").text(result.total);
                    // 1、解析并显示员工数据
                    buildUsersTab(result);
                    // 2、解析显示分页信息
                    buildNavTab(result);
                }
            });
        })

        // 获取第几页的数据
        function toPage(pn) {
            console.log("获取第" + pn  + "页数据");
            $.ajax({
                url: "user/users",
                data: "pn="+pn,
                type:"GET",
                success:function (result) { // 这里面是不是就包括有当前页是第几页
                    // console.log("第" + pn +"页数据",result)
                    // 重新构建数据table
                    buildUsersTab(result);
                    // 重新构建分页条
                    buildNavTab(result);
                    // 更新表格左下角的页码
                    updateCurrentPage(result.pageNum);
                }
            });
        }

        function updateCurrentPage(pageNum) {
            $("#currentPage").text(pageNum);
        }

        // 构建分页条
        function buildNavTab(result) {

            // $("#userstab tbody").empty(); // 这个是去掉表格数据
            $("#pnav").empty();
            console.log(result.hasPreviousPage+ "---",result);
            var ul = $("<ul></ul>").addClass("pagination")
            var firstPageLi = $("<li></li>").append($("<a onclick='toPage(1)'></a>").append("首页").attr("href","#"));
            var prePageLi;
            var nexPageLi;
            if (!result.hasPreviousPage) {
                prePageLi = $("<li></li>").addClass("disabled").append($("<a onclick='toPage("+(result.pageNum-1)+")'></a>").append("&laquo;").attr("href","#")); // 上一页
            } else {
                prePageLi = $("<li></li>").append($("<a onclick='toPage("+(result.pageNum-1)+")'></a>").append("&laquo;").attr("href","#")); // 上一页
            }
            if (!result.hasNextPage) {
                nexPageLi = $("<li></li>").addClass("disabled").append($("<a onclick='toPage("+(result.pageNum+1)+")'></a>").append("&raquo;").attr("href","#")); // 下一页
            } else {
                nexPageLi = $("<li></li>").append($("<a onclick='toPage("+(result.pageNum+1)+")'></a>").append("&raquo;").attr("href","#")); // 下一页
            }

            var lastPageLi = $("<li></li>").append($("<a onclick='toPage("+result.pages+")'></a>").append("尾页").attr("href","#"));
            ul.append(firstPageLi).append(prePageLi);
            // 遍历总的页数
            $.each(result.navigatepageNums,function (index,item){ // item 是分页条上的页码
                // 选中页要成为激活状态active
                var numli;
                if (result.pageNum == item) { // 后台返回的数据显示在表格里的页的数据（有个第几页） == 当前点的页码
                    numli = $("<li></li>").addClass("active").append($("<a onclick='toPage("+item+")'></a>").append(item));
                } else {
                    numli = $("<li></li>").append($("<a onclick='toPage("+item+")'></a>").append(item));
                }
                ul.append(numli);
            });


            ul.append(nexPageLi).append(lastPageLi);
            var nav = $("<nav></nav>").append(ul);
            nav.appendTo("#pnav");
        }

        function buildUsersTab(obj) {
            $("#userstab tbody").empty();
            // 得到obj中的LIST
            var users = obj.list;
            // users：遍历的集合list
            // item：每一条数据
            $.each(users, function (index, item) {
                var id = $("<td></td>").append(item.id);
                var user_id = $("<td></td>").append(item.userId);
                var user_name = $("<td></td>").append(item.userName);
                var user_age = $("<td><div class='progress'> <div class='progress-bar progress-bar-success' style='width: "+item.userAge+"%'> <span class='sr-only'>(item.userAge)% Complete (success)</span></div><div class='progress-bar progress-bar-warning progress-bar-striped' style='width: "+(100 - item.userAge)+"%'><span class='sr-only'>(100 - item.userAge)% Complete (warning)</span></div></div></td>");
                var user_pwd = $("<td></td>").append(item.userPwd);
                var user_realname = $("<td></td>").append(item.userRealname);
                var user_img = $("<td></td>").append(item.userImg);
                var editBtn = $("<button data-toggle='modal' data-target='#exampleModal'onclick='update("+item.id+")'>编辑</button>").addClass("btn btn-success");
                var deleteBtn = $("<button onclick='deleteData("+item.id+")'>删除</button>").addClass("btn btn-danger");
                var btnTd = $("<td></td>").append(editBtn).append(deleteBtn);
                $("<tr></tr>")
                    .append(id)
                    .append(user_id)
                    .append(user_name)
                    .append(user_age)
                    .append(user_pwd)
                    .append(user_realname)
                    .append(user_img)
                    .append(btnTd)
                    .appendTo("#userstab tbody");
            });
        }

        //添加用户
        function saveData(){
            let userName = document.getElementById("inputUserName").value;
            let userPwd = document.getElementById("inputPwd").value;
            let userRealname = document.getElementById("inputRealname").value;
            let user = {
                userName: userName,
                userPwd :  userPwd,
                userRealname : userRealname
            };
            $.ajax({
                url:'user/insert',
                data:JSON.stringify(user),
                type:'post',
                dataType:'text',
                contentType: "application/json;charset=utf-8",
                success:function (res){
                    console.log("res:",res);
                    $("#myModal").modal('hide');
                    $("#currentPage").text(res.pageNum);
                    $("#pages").text(res.pages);
                    $("#total").text(res.total);
                },
                complete:function (err){//如果出错，这里会显示出错误信息
                    console.log("err:",err)
                }
            });
        }

        //删除用户
        function deleteData(id){
            alert(id)
            $.ajax({
                url:'user/delete/'+id,
                type:'delete',
                dataType: 'text',
                contentType: 'application/json;charset=utf-8',
                success:function (res){
                    console.log("res:",res);
                    $("#currentPage").text(res.pageNum);
                    $("#pages").text(res.pages);
                    $("#total").text(res.total)
                },
                complete:function (err){
                    console.log("err:",err)
                }
            });
        }

        //编辑用户
        function update(id){
            $("#Id").val(id);
        }
        function updateData(){
            let id = $("#Id").val();
            let userName = document.getElementById("recipient-name").value;
            let userPwd = document.getElementById("message-text1").value;
            let userRealname = document.getElementById("message-text2").value;
            let user = {
                id : id,
                userName: userName,
                userPwd : userPwd,
                userRealname : userRealname
            };
            $.ajax({
                url:'user/update',
                data:JSON.stringify(user),
                type:'put',
                dataType:'text',
                contentType:'application/json;charset=utf-8',
                success:function (res){
                    console.log("res:",res);
                    $("#exampleModal").modal('hide');
                    $("#currentPage").text(res.pageNum);
                    $("#pages").text(res.pages);
                    $("#total").text(res.total)
                },
                complete:function (err){
                    console.log("err:",err)
                }
            });
        }

        //查询
        function selectId(){
            let id =document.getElementById("userId").value;
            $.ajax({
                url: 'user/selectId',
                data:{
                    id : id
                },
                type:'get',
                dataType:'json',
                contentType:'application/json;charset=utf-8',
                success:function (result){
                    console.log("res:",result)
                    buildUsersTab(result);
                    // 重新构建分页条
                    buildNavTab(result);
                    // 更新表格左下角的页码
                    updateCurrentPage(result.pageNum);
                },
                complete:function (err){
                    console.log("err:",err)
                }
            });

        }
    </script>
</head>
<body>
<input type="text" id="Id" value="">
<!--<form class="form-inline">-->
    <div class="form-group">
        <input id="userId" type="text" class="form-control" />
    </div>
    <div class="form-group">
        <button class="btn btn-warning" onclick="selectId()">查询</button>
        <button class="btn btn-info">更新</button>
        <button class="btn btn-danger">删除</button>

        <!-- Button trigger modal -->
        <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">
            添加
        </button>

        <!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">添加用户</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label for="inputUserName" class="col-sm-2 control-label">用户名称</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="inputUserName" placeholder="请输入名称">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputPwd" class="col-sm-2 control-label">用户密码</label>
                                <div class="col-sm-10">
                                    <input type="password" class="form-control" id="inputPwd" placeholder="请输入密码">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputRealname" class="col-sm-2 control-label">真实姓名</label>
                                <div class="col-sm-10">
                                    <input type="text" class="form-control" id="inputRealname" placeholder="请输入真实姓名">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inputImg" class="col-sm-2 control-label">头像</label>
                                <div class="col-sm-10">
                                    <input type="file" class="form-control" id="inputImg">
                                    <img src="https://tse2-mm.cn.bing.net/th/id/OIP-C.f1wrwfBJ4hJT6b5GE_AfggHaE7?w=229&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7" alt="..." class="img-rounded" style="max-width: 30%">
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-default">Sign in</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="saveData()">保存数据</button>
                    </div>
                </div>
            </div>
        </div>



        <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="exampleModalLabel">编辑用户</h4>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="recipient-name" class="control-label">用户名称：</label>
                                <input type="text" class="form-control" id="recipient-name">
                            </div>
                            <div class="form-group">
                                <label for="message-text1" class="control-label">用户密码：</label>
                                <textarea class="form-control" id="message-text1"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="message-text2" class="control-label">真实姓名：</label>
                                <textarea class="form-control" id="message-text2"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="message-text3" class="col-sm-2 control-label">头像</label>
                                <div class="col-sm-10">
                                    <input type="file" class="form-control" id="message-text3">
                                    <img src="https://tse2-mm.cn.bing.net/th/id/OIP-C.f1wrwfBJ4hJT6b5GE_AfggHaE7?w=229&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7" alt="..." class="img-rounded" style="max-width: 30%">
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" onclick="updateData()">保存数据</button>
                    </div>
                </div>
            </div>
        </div>
<!--</form>-->
<table class="table table-striped" id="userstab">
    <thead>
    <th>#</th>
    <th>用户编号</th>
    <th>用户名称</th>
    <th>生命倒计时</th>
    <th>用户密码</th>
    <th>真实姓名</th>
    <th>头像</th>
    <th>操作</th>
    </thead>
    <tbody>
    <!-- 显示遍历出来的用户数据 -->
    </tbody>
    <tfoot>
    <tr>
        <td colspan="3">
            当前<span id="currentPage"></span>页，共有<span id="pages"></span>页，共有<span id="total"></span>条数据

        </td>
        <td colspan="5" align="center">

            <nav aria-label="Page navigation" id="pnav">
                <%--        <ul class="pagination">--%>
                <%--          <li class="disabled">--%>
                    <%--            <a href="#" aria-label="Previous">--%>
                        <%--              <span aria-hidden="true">&laquo;</span>--%>
                        <%--            </a>--%>
                    <%--          </li>--%>
                <%--          <li><a href="#">1</a></li>--%>
                <%--          <li class="active"><a href="#">2</a></li>--%>
                <%--          <li><a href="#">3</a></li>--%>
                <%--          <li><a href="#">4</a></li>--%>
                <%--          <li><a href="#">5</a></li>--%>
                <%--          <li>--%>
                    <%--            <a href="#" aria-label="Next">--%>
                        <%--              <span aria-hidden="true">&raquo;</span>--%>
                        <%--            </a>--%>
                    <%--          </li>--%>
                <%--        </ul>--%>
            </nav>
        </td>
    </tr>
    </tfoot>
</table>
</body>

</html>